package br.ufmg.ubicomp.droidguide.communication;

import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Collection;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import br.ufmg.ubicomp.droidguide.common.DroidGuideConfigurationManager;
import br.ufmg.ubicomp.droidguide.common.DroidGuideConstants;
import br.ufmg.ubicomp.droidguide.common.DroidGuideEntity;
import br.ufmg.ubicomp.droidguide.common.EntityProperties;
import br.ufmg.ubicomp.droidguide.profile.UserProfile;
import br.ufmg.ubicomp.droidguide.profile.UserProfileFactoryImpl;
import br.ufmg.ubicomp.droidguide.utils.XmlParseUtil;

public class ProfileCommunicationService extends CommunicationService{

	public static final String BASE_URL = "http://droidguide.appspot.com/user_profile/";
	//public static final String BASE_URL = "http://10.0.2.2:8080/user_profile/";

	public static DroidGuideEntity read(String key) throws Exception {
		String url = BASE_URL + "read?key=" + key;

		NodeList entities = processRequest(url);

		UserProfile profile = new UserProfileFactoryImpl().createUserProfile();

		for (int i = 0; i < entities.getLength(); i++) {
			Node entityEntry = entities.item(i);

			if (entityEntry instanceof Element) {
				Element entityElement = (Element) entityEntry;

				if (entityElement.getAttribute("kind").equals("UserProfile")) {
					getProfileObject(profile, entityElement);
				}
			}
		}
		return profile;
	}

	public static UserProfile getUserProfile() throws Exception {
		String dgKey = DroidGuideConfigurationManager.getInstance().getData(
				DroidGuideConstants.DROID_GUIDE_USER_KEY);
		
		String url = DroidGuideConfigurationManager.getInstance().getData("server") + 
			"user_profile/process?operation=get&droidGuideUser_key="+dgKey;

		NodeList entities = processRequest(url);

		UserProfile profile = null; 
			//new UserProfileFactoryImpl().createUserProfile();

		for (int i = 0; i < entities.getLength(); i++) {
			Node entityEntry = entities.item(i);

			if (entityEntry instanceof Element) {
				Element entityElement = (Element) entityEntry;

				if (entityElement.getAttribute("kind").equals("UserProfile")) {
					profile = new UserProfile();
					getProfileObject(profile, entityElement);
				}
			}
		}
		return profile;
	}

	private static void getProfileObject(UserProfile profile,
			Element entityElement) throws UnsupportedEncodingException {
		profile.setKey(entityElement.getAttribute("key"));

		NodeList properties = entityElement.getChildNodes();

		for (int j = 0; j < properties.getLength(); j++) {
			Node propertyEntry = properties.item(j);

			if (propertyEntry instanceof Element) {
				Element propertyElement = (Element) propertyEntry;

				Text textNode = (Text) propertyElement
						.getFirstChild();
				String text = URLDecoder.decode(textNode.getData().trim(), "UTF-8");

				if (propertyElement.getTagName().equals("property")) {
					String attributeName = propertyElement
							.getAttribute("name");
					if (attributeName.equals("name")) {
						profile.setName(text);
					} else if (attributeName.equals("birth_year")) {
						profile
								.setBirthyear(Integer
										.parseInt(text));
					} else if (attributeName.equals("gender")) {
						profile.setGender(text.charAt(0));
					} else if (attributeName
							.equals("marital_status")) {
						profile.setMaritalstatus(text);
					} else if (attributeName.equals("food")) {
						profile.setFood(Boolean.parseBoolean(text
								.toLowerCase()));
					} else if (attributeName.equals("drink")) {
						profile.setDrink(Boolean.parseBoolean(text
								.toLowerCase()));
					} else if (attributeName.equals("style")) {
						profile.setStyle(text.charAt(0));
					} else if (attributeName.equals("consumer")) {
						profile.setConsumer(Byte.valueOf(text));
					} else if (attributeName.equals("historical")) {
						profile.setHistorical(Byte.valueOf(text));
					} else if (attributeName.equals("ecological")) {
						profile.setEcological(Byte.valueOf(text));
					} else if (attributeName.equals("gastronomic")) {
						profile.setGastronomic(Byte.valueOf(text));
					} else if (attributeName.equals("cultural")) {
						profile.setCultural(Byte.valueOf(text));
					} else if (attributeName.equals("bohemian")) {
						profile.setBohemian(Byte.valueOf(text));
					} else if (attributeName.equals("weather")) {
						profile.setWeather(Boolean.getBoolean(text
								.toLowerCase()));
					} else if (attributeName.equals("traffic")) {
						profile.setTraffic(Boolean.getBoolean(text
								.toLowerCase()));
					}
				}
			}
		}
	}

	public static String saveUserProfile(UserProfile profile) throws Exception {
		String dgKey = DroidGuideConfigurationManager.getInstance().getData(
				DroidGuideConstants.DROID_GUIDE_USER_KEY);
		
		String url = DroidGuideConfigurationManager.getInstance().getData("server") + 
			"user_profile/process?operation=save&droidGuideUser_key="+dgKey;
		
		/* Build URL */
		
		url = url + "&name=" + URLEncoder.encode(profile.getName(), "UTF-8");
		url = url + "&gender=" + profile.getGender();
		url = url + "&birth_year=" + profile.getBirthyear();
		url = url + "&marital_status=" + URLEncoder.encode(profile.getMaritalstatus(), "UTF-8");
		url = url + "&food=" + (profile.getFood()?1:0);
		url = url + "&drink=" + (profile.getDrink()?1:0);
		url = url + "&style=" + profile.getStyle();
		url = url + "&consumer=" + profile.getConsumer();
		url = url + "&historical=" + profile.getHistorical();
		url = url + "&ecological=" + profile.getEcological();
		url = url + "&gastronomic=" + profile.getGastronomic();
		url = url + "&cultural=" + profile.getCultural();
		url = url + "&bohemian=" + profile.getBohemian();
		url = url + "&weather=" + (profile.getWeather()?1:0);
		url = url + "&traffic=" + (profile.getTraffic()?1:0);
		
		NodeList entities = processRequest(url);
		Collection<EntityProperties> list = 
			XmlParseUtil.getEntities(entities);
		
		String sb = "";
		for (EntityProperties ep: list)
		{
			if (ep.getKind().equals("profile"))
			{
				sb = ep.getValue("key");
			}
		}
		
//		char[] buf = new char[1024];
//		StringBuilder sb = new StringBuilder();
//		while (reader.read(buf) >= 0) {
//		  sb.append(buf);
//		}
		return sb;
	}
	
//	@Deprecated
//	public static String updateUserProfile(UserProfile profile) throws Exception {
//		String url = BASE_URL + "save?";
//		
//		/* Build URL */
//		url = url + "key=" + URLEncoder.encode(profile.getKey(), "UTF-8");
//		url = url + "&name=" + URLEncoder.encode(profile.getName(), "UTF-8");
//		url = url + "&gender=" + profile.getGender();
//		url = url + "&birth_year=" + profile.getBirthyear();
//		url = url + "&marital_status=" + URLEncoder.encode(profile.getMaritalstatus(), "UTF-8");
//		url = url + "&food=" + (profile.getFood()?1:0);
//		url = url + "&drink=" + (profile.getDrink()?1:0);
//		url = url + "&style=" + profile.getStyle();
//		url = url + "&consumer=" + profile.getConsumer();
//		url = url + "&historical=" + profile.getHistorical();
//		url = url + "&ecological=" + profile.getEcological();
//		url = url + "&gastronomic=" + profile.getGastronomic();
//		url = url + "&cultural=" + profile.getCultural();
//		url = url + "&bohemian=" + profile.getBohemian();
//		url = url + "&weather=" + (profile.getWeather()?1:0);
//		url = url + "&traffic=" + (profile.getTraffic()?1:0);
//		
//		/* Make request */
////		DefaultHttpClient client = new DefaultHttpClient();
////		HttpGet method = new HttpGet(url);
//		/*
//		method.addHeader("key", profile.getKey());
//		method.addHeader("name", profile.getName());
//		method.addHeader("gender", Character.toString(profile.getGender()));
//		method.addHeader("birth_year", Integer.toString(profile.getBirthyear()));
//		method.addHeader("marital_status", profile.getMaritalstatus());
//		method.addHeader("food", Boolean.toString(profile.getFood()));
//		method.addHeader("drink", Boolean.toString(profile.getDrink()));
//		method.addHeader("style", Integer.toString(profile.getStyle()));
//		method.addHeader("consumer", Integer.toString(profile.getConsumer()));
//		method.addHeader("historical", Integer.toString(profile.getHistorical()));
//		method.addHeader("ecological", Integer.toString(profile.getEcological()));
//		method.addHeader("gastronomic", Integer.toString(profile.getGastronomic()));
//		method.addHeader("cultural", Integer.toString(profile.getCultural()));
//		method.addHeader("bohemian", Integer.toString(profile.getBohemian()));
//		method.addHeader("weather", Boolean.toString(profile.getWeather()));
//		method.addHeader("traffic", Boolean.toString(profile.getTraffic()));
//		*/
////		HttpResponse response = client.execute(method);
////		if (response.getStatusLine().getStatusCode() != 200) {
////		  return null;
////		}
////		HttpEntity entity = response.getEntity();
////		InputStream inStream = entity.getContent();
////		Reader reader = new InputStreamReader(inStream);
////		char[] buf = new char[1024];
////		StringBuilder sb = new StringBuilder();
////		while (reader.read(buf) >= 0) {
////		  sb.append(buf);
////		}
////		return sb.toString();
//		return execute
//	}

}
